package com.team.employment.web.admin.custom.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;


/**
 * 用于配置 BCryptPasswordEncoder Bean
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Profile("app")  //仅前台生效
    public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/app/**",
                                "/doc.html",
                                "/v3/api-docs/**",
                                "/webjars/**",
                                "/swagger-ui/**",
                                "/swagger-resources/**",
                                "/favicon.ico"

                        ).permitAll()
                        .anyRequest().denyAll()  // 其他请求直接拒绝
                );
        return http.build();
    }
    @Bean
    @Profile("dev") //仅在开发环境中生效
    public SecurityFilterChain devSecurityFilterChain(HttpSecurity http) throws Exception{
//        验证请求是否真的走 dev 配置
//        System.out.println(">>>>>> Dev Security Config Loaded <<<<<<");
        http
                .csrf(csrf -> csrf.disable())  // 禁用 CSRF,Spring Security 默认启用 CSRF 防护，会拦截 POST/PUT/DELETE 请求
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))  // 启用 CORS
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/admin/**",
                                "/doc.html",
                                "/v3/api-docs/**",
                                "/webjars/**",          // 添加Knife4j的webjars资源
                                "/favicon.ico",         // 添加favicon
                                "/swagger-resources/**", // Swagger资源
                                "/swagger-ui/**",      // Swagger UI资源
                                "/swagger-ui.html"      // 传统Swagger UI
                        ).permitAll()
                        .requestMatchers("/admin/userAction/registerCompany").hasAnyAuthority("ENTREPRENEURS","admin") // 允许管理员、企业者权限
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form.disable());  // 关键：禁用表单登录
//                .httpBasic(basic -> basic.disable()); // 禁用 Basic Auth

        return http.build();
    }

    @Bean
    @Profile({"prod", "test"}) // 生产/测试环境生效
    public SecurityFilterChain prodSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
        return http.build();
    }

    // CORS 配置(前后台共用)
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080",//后台端口
                "http://localhost:8081" //前台端口
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    //借助 UserDetailsService 接口从数据库中加载用户信息
    @Bean
    public UserDetailsService userDetailsService(){
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("username")
                        .password("password")
                        .roles("admin")
                        .authorities("ENTREPRENEURS")
                        .build();
        return new InMemoryUserDetailsManager(user);
    }

}
